<?php
namespace app\home\controller;
use think\Controller;
use think\facade\App;
use think\facade\Config;
use think\facade\Request;

class Base extends Controller {
    
    /**
     * @desc 用户ID
     * @var int
     */
    protected $userId = 0;
    
    /**
     * @desc 用户基础信息
     * @var array
     */
    protected $userInfo = [];
    
    /**
     * @desc 网站配置
     * @var array
     */
    protected $siteConfig = [];
    
    /**
     * @desc 初始化
     */
    protected function initialize() {
        $controller = strtolower(Request::controller());
        $action = strtolower(Request::action(true));
    
        //检测登录
        $this->userId  = session('userId') ?: 0;
        if ($this->userId) {
            $field = [
                'user_id as userId',
                'user_name as userName',
                'user_phone as userPhone',
                'user_email as userEmail',
                'user_icon as userIcon',
                'user_level as userLevel',
                'user_secret_id as secretId',
                'user_secret_key as secretKey',
            ];
            $this->userInfo = App::model('User')
                ->field($field)
                ->where('user_id', '=', $this->userId)
                ->find();

            if(!$this->userInfo) {
                session('userId', null);
                $this->redirect(url('user/login'));
            }
        }

        //网站配置信息
        $this->siteConfig = model('SiteConfig')->getSiteConfig();

        //赋初始值防止模板报错
        $this->assign('userId', $this->userId);
        $this->assign('userInfo', $this->userInfo);
        $this->assign('controller_action', $controller.'_'.$action);
        $this->assign('siteConfig', $this->siteConfig);
    }
    
    /**
     * @desc 检测是否登录
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function checkLogin() {
        if (!$this->userId) {
            session('userId', null);
            $this->redirect(url('user/login'));
        }
    }
}
